//
//  KSNetRequest.m
//  Test
//
//  Created by KS on 15/11/24.
//  Copyright © 2015年 xianhe. All rights reserved.
//
#import "KSCache.h"

#import "KSNetRequest.h"
#import <AFNetworking.h>
#import "ProgressHUD.h"
#import "UIViewController+KSNoNetController.h"

//===========================请求超时时间==========================//
#define TIMEOUTINTERVAL 30
//====================是不是需要缓存==YES需要==NO不需要====================//
#define ISCACHE YES

#define Image_Name @"image"

@interface KSNetRequest ()

@end

@implementation KSNetRequest

/**
 *  判断网络状态的POST请求
 */
+ (void)requestTarget:(UIViewController*)target method:(nonnull NSString*)method url:(nonnull NSString*)URLString parameters:(nullable id)parameters success:(requestSuccess)success failure:(requestFailure)failure
{
    if ([self checkNetState]) {
        [target hiddenNonetWork];
        
        [self requestCache:method url:URLString parameters:parameters success:success failure:failure];
        
    }else{
        [target showNonetWork];
    
        success?success(nil,nil):nil;
        failure?failure(nil,nil):nil;
    }
}

/**
 *  添加Cache
 */
+ (void)requestCache:(nonnull NSString*)method url:(nonnull NSString*)URLString parameters:(nullable id)parameters success:(requestSuccess)success failure:(requestFailure)failure
{
    
    if (ISCACHE) {
        success(nil,[KSCache selectObjectWithURL:URLString parameter:parameters]);
        [self requestProgress:method url:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            #warning warning
            //=====这个判断需要和后台协商，什么情况下请求成功=然后才可以缓寸=====================================================//
            if ([responseObject[@"result"] isEqualToString:@"0"]) {
            //======================================================//
                [KSCache updateObject:responseObject withURL:URLString parameter:parameters];
                
            }
            success?success(task,responseObject):nil;
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            failure?failure(task,error):nil;
        }];
    }else{
        [self requestProgress:method url:URLString parameters:parameters success:success failure:failure];
    }
}
/**
 *  带活动指示器的请求
 */
+ (void)requestProgress:(nonnull NSString*)method url:(nonnull NSString*)URLString parameters:(nullable id)parameters success:(nullable requestSuccess)success failure:(nullable requestFailure)failure
{
    [ProgressHUD show:@"Loading..."];
    
    if ([method isEqualToString:@"POST"]) {
        [self requestPOST:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            [ProgressHUD dismiss];
            
            success?success(task,responseObject):nil;
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            [ProgressHUD dismiss];
            
            failure?failure(task,error):nil;
        }];
    }else{
    
        [self requestGET:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            [ProgressHUD dismiss];
            
            success?success(task,responseObject):nil;
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            [ProgressHUD dismiss];
            
            failure?failure(task,error):nil;
        }];
    }
}
/**
 *  基本POST请求
 */
+ (void)requestPOST:(nonnull NSString*)URLString parameters:(nullable id)parameters success:(requestSuccess)success failure:(requestFailure)failure
{
    AFHTTPSessionManager* manager = [self getManager];
    
    [manager POST:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        //先判断是否有回调，然后回调
        success?success(task,responseObject):nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //如果有回调，则返回处理
        failure?failure(task,error):NSLog(@"%@",error.localizedDescription);
    }];
    
}
/**
 *  基本GET请求
 */
+(void)requestGET:(NSString *)URLString parameters:(nullable id)parameters success:(requestSuccess)success failure:(requestFailure)failure
{
    AFHTTPSessionManager* manager = [self getManager];
    
    [manager GET:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        //先判断是否有回调，然后回调
        success?success(task,responseObject):nil;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        //如果有回调，则返回处理
        failure?failure(task,error):NSLog(@"%@",error.localizedDescription);
    }];
}

/**
 *  同步上传图片（多张）
 */
+ (nonnull NSString *)postRequestWithURL: (nonnull NSString *)url
                              postParems: (nullable NSMutableDictionary *)postParems
                             picFilePath: (nullable NSMutableArray *)picFilePath
                             picFileName: (nullable NSMutableArray *)picFileName
{
    [ProgressHUD show:@"upload..."];
    
    NSString *hyphens = @"--";
    NSString *boundary = @"*****";
    NSString *end = @"\r\n";
    
    NSMutableData *myRequestData1=[NSMutableData data];
    //遍历数组，添加多张图片
    for (int i = 0; i < picFilePath.count; i ++) {
        NSData* data;
        UIImage *image=[UIImage imageWithContentsOfFile:[picFilePath objectAtIndex:i]];
        //判断图片是不是png格式的文件
        if (UIImagePNGRepresentation(image)) {
            //返回为png图像。
            data = UIImagePNGRepresentation(image);
        }else {
            //返回为JPEG图像。
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        
        //所有字段的拼接都不能缺少，要保证格式正确
        [myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
        [myRequestData1 appendData:[boundary dataUsingEncoding:NSUTF8StringEncoding]];
        [myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSMutableString *fileTitle=[[NSMutableString alloc]init];
        //要上传的文件名和key，服务器端用file接收
        [fileTitle appendFormat:@"Content-Disposition:form-data;name=\"%@\";filename=\"%@\"",[NSString stringWithFormat:@"file%d",i+1],[NSString stringWithFormat:@"image%d.png",i+1]];
        
        [fileTitle appendString:end];
        
        [fileTitle appendString:[NSString stringWithFormat:@"Content-Type:application/octet-stream%@",end]];
        [fileTitle appendString:end];
        
        [myRequestData1 appendData:[fileTitle dataUsingEncoding:NSUTF8StringEncoding]];
        
        [myRequestData1 appendData:data];
        
        [myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
    }
    
    
    [myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
    [myRequestData1 appendData:[boundary dataUsingEncoding:NSUTF8StringEncoding]];
    [myRequestData1 appendData:[hyphens dataUsingEncoding:NSUTF8StringEncoding]];
    [myRequestData1 appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    //参数的集合的所有key的集合
    NSArray *keys= [postParems allKeys];
    
    //添加其他参数
    for(int i=0;i<[keys count];i++)
    {
        
        NSMutableString *body=[[NSMutableString alloc]init];
        [body appendString:hyphens];
        [body appendString:boundary];
        [body appendString:end];
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //添加字段名称
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"",key];
        
        [body appendString:end];
        
        [body appendString:end];
        //添加字段的值
        [body appendFormat:@"%@",[postParems objectForKey:key]];
        
        [body appendString:end];
        
        [myRequestData1 appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
    }
    
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:20];
    
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",boundary];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%ld", [myRequestData1 length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData1];
    //http method
    [request setHTTPMethod:@"POST"];
    
    NSHTTPURLResponse *urlResponese = nil;
    NSError *error = [[NSError alloc]init];
    
    NSData* resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponese error:&error];
    NSString* result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    
    if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){
        NSLog(@"返回结果=====%@",result);
//        SBJsonParser *parser = [[SBJsonParser alloc ] init];
//        NSDictionary *jsonobj = [parser objectWithString:result];
        NSDictionary *jsonobj = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableContainers error:&error];
        if (jsonobj == nil || (id)jsonobj == [NSNull null] || [[jsonobj objectForKey:@"flag"] intValue] == 0)
        {
            
            dispatch_async(dispatch_get_main_queue(), ^{
//                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"提交失败." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                [alert show];
                [ProgressHUD showError:@"提交失败"];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
//                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"提交成功." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                [alert show];
                [ProgressHUD showSuccess:@"提交成功"];
            });
        }
        
        return result;
    }
    else if (error) {
        NSLog(@"%@",error);
        [ProgressHUD showError:@"提交失败"];
//        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"提交失败." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
        return nil;
        
    }
    else
        return nil;
}

/**
 * AFN上传图片
 */
-(void)postImageWithURL:(nonnull NSString *)urlStr parameters:(nullable id)params array:(nullable NSMutableArray *)imageDataArray
{
    // 向服务器提交图片
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 显示进度
    [manager POST:urlStr parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         if (imageDataArray.count == 0) {
             static int nindex = 1;
             // 单张图片上传
             NSString * paramName = [NSString stringWithFormat:@"%@%zi", Image_Name, nindex];
             NSString * newImageName = [NSString stringWithFormat:@"%@.jpg", paramName];
             NSString * imagepath = NSHomeDirectory();
             NSString * path = [imagepath stringByAppendingPathComponent:@"Documents"];
             NSBundle * Bundle = [NSBundle bundleWithPath:path];
             NSURL    * fileURL = [Bundle URLForResource:newImageName withExtension:nil];
             [formData appendPartWithFileURL:fileURL name:paramName error:nil];
         }else{
             // 上传 多张图片
             for(NSInteger i = 0; i < imageDataArray.count; i++)
             {
                 NSData * imageData = [imageDataArray objectAtIndex: i];
                 // 上传的参数名
                 NSString * Name = [NSString stringWithFormat:@"%@%zi", Image_Name, i+1];
                 // 上传filename
                 NSString * fileName = [NSString stringWithFormat:@"%@.jpg", Name];
                 
                 [formData appendPartWithFileData:imageData name:Name fileName:fileName mimeType:@"image/jpeg"];
             }
         }
     }
          success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         
         NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
         NSLog(@"完成 %@", result);
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"错误 %@", error.localizedDescription);
     }];
}

/**
 *  判断网络状态
 *
 *  @return 返回状态 YES 为有网 NO 为没有网
 */
+ (BOOL)checkNetState
{ 
    return [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus > 0;
}

/**
 *  创建请求者
 *
 *  @return AFHTTPSessionManager
 */
+ (AFHTTPSessionManager*)getManager
{
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    
    //设置请求超时
    manager.requestSerializer.timeoutInterval = TIMEOUTINTERVAL;
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"html/text",@"text/json",nil];
    return manager;
}

@end
